package com.cpi.cornpp.instructionspurchases.service;

import java.text.MessageFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.util.MessageResources;

import com.cpi.conrpp.mail.Email;
import com.cpi.conrpp.mail.EmailSender;
import com.cpi.cornpp.instructionspurchases.view.InstructionPurchaseCreateView;
import com.cpi.cornpp.product.view.ProductView;
import com.cpi.cornpp.purchaseinstructiondetail.exception.InstructionPurchaseDetailException;
import com.cpi.cornpp.purchaseinstructiondetail.service.InstructionPurchaseDetailService;
import com.cpi.cornpp.purchaseinstructiondetail.view.InstructionPurchaseDetailView;
import com.cs.common.init.SystemParameterCollection;

public class InstructionPurchaseMailService extends EmailSender {

	private static final String CIMAPLANNING_PURCHASER_MAIL = "CIMAPLANNING_PURCHASER_MAIL";
	private static final String CIMAPLANNINGMAIL = "CIMAPLANNINGMAIL";
	private static final String LABEL_SUBJECT_TEMPLATE = "label.mail.purchase.order.subject";
	private static final String LABEL_BODY_TEMPLATE = "label.mail.purchase.order.body";
	private static final String SUBJECT_ACTION_ADD = "label.mail.purchase.order.subject.action.add";
	private static final String BODY_ACTION_ADD = "label.mail.purchase.order.body.action.add";
	private static final String SUBJECT_ACTION_UPDATE = "label.mail.purchase.order.subject.action.update";
	private static final String BODY_ACTION_UPDATE = "label.mail.purchase.order.body.action.update";
	private static final String LABEL_HEADER_STYLES = "<style> .titulocolumna {  padding: 1px 0 2px 2px;   font-size: 8pt;   padding-bottom: 2px;   " +
			"margin-top: 2px; 	margin-right: 0pt;   margin-bottom: 2px;   margin-left: 0pt;} " +
			" .columnadatoNon { font-family: Arial, Helvetica, sans-serif; 	font-size: 10px; font-weight: normal; 	text-align: center; " +
		     " color:#003366; 	background: #F0F4FB; 	} " + 
		    ".columnadatoPar { font-family: Arial, Helvetica, sans-serif; font-size: 10px; font-weight: normal; text-align: center; " +
		    " color:#003366; background: #FFFFFF; }</style>";
	private static final String CIMMAPLANNINGMAIL_CC = "CIMMAPLANNINGMAIL_CC";
	private static final String INSTRUCTION_PURCHASE_REFERENCE_LENGTH_CODE = "INSTRUCTION_PURCHASE_REFERENCE_LENGTH_CODE";

	/**
	 * 
	 * @param view
	 * @param messageResources
	 * @param instructionPurchaseFormDetails 
	 * @param addAction
	 * @return
	 */	
	public Email buildMailForAddOrUpdateAction(InstructionPurchaseCreateView view, MessageResources messageResources, List instructionPurchaseFormDetails, Locale locale, boolean addAction){
		String purchaserMail = SystemParameterCollection.getInstance().getSystemParameterBean(CIMAPLANNING_PURCHASER_MAIL).getValue();
		String ccMail = SystemParameterCollection.getInstance().getSystemParameterBean(CIMMAPLANNINGMAIL_CC).getValue();
		String cimmaPlanningMail = SystemParameterCollection.getInstance().getSystemParameterBean(CIMAPLANNINGMAIL).getValue();
		int padding = SystemParameterCollection.getInstance().getSystemParameterBean(INSTRUCTION_PURCHASE_REFERENCE_LENGTH_CODE).getIntValue();
		
		String purchaserMails[];
		String ccMails[]; 

		String subjectTemplate  = null;		
		String subject = null;
		String bodyTemplate = null;
		StringBuffer body = null;
		Email email = null;
		subjectTemplate = messageResources.getMessage(locale, LABEL_SUBJECT_TEMPLATE);
		bodyTemplate = messageResources.getMessage(locale, LABEL_BODY_TEMPLATE);
		
		if(addAction){
			Object[] paramsSubject = { messageResources.getMessage(locale, SUBJECT_ACTION_ADD),  StringUtils.leftPad(String.valueOf(view.getId()),padding,"0")};
			Object[] paramsBody = { messageResources.getMessage(locale, BODY_ACTION_ADD)};
			subject = MessageFormat.format(subjectTemplate, paramsSubject);
			body = new StringBuffer(MessageFormat.format(bodyTemplate, paramsBody));			
		}else{
			Object[] paramsSubject = { messageResources.getMessage(locale, SUBJECT_ACTION_UPDATE), StringUtils.leftPad(String.valueOf(view.getId()),padding,"0")};
			Object[] paramsBody = { messageResources.getMessage(locale, BODY_ACTION_UPDATE)};
			subject = MessageFormat.format(subjectTemplate, paramsSubject);
			body = new StringBuffer(MessageFormat.format(bodyTemplate, paramsBody));			
		}
		if(instructionPurchaseFormDetails!=null){
			body.append(purchaseOrderHTMLSimplified(instructionPurchaseFormDetails,messageResources, locale));
			
		}
		email = new Email();
		email.setFrom(cimmaPlanningMail);
		
		purchaserMails = purchaserMail.split(",");
		for (int index = 0; index < purchaserMails.length; index++) {
			email.addToRecipient(purchaserMails[index]);
		}

		ccMails = ccMail.split(",");
		for (int index = 0; index < ccMails.length; index++) {
			email.addCcRecipient(ccMails[index]);
		}
		
		email.setSubject(subject);
		email.setBody(body.toString());
		return email;
		
	}
	
	
	
	/**
	 * Detalle de la orden de compra en formato HTML sin
	 * los botones de modificar...
	 * @param messageResources 
	 * @return
	 */
	public String purchaseOrderHTMLSimplified(List instructionPurchaseFormDetails, MessageResources messageResources, Locale locale ){		
		String detailTemplate = null;
		String detail = null;
		StringBuffer html = new StringBuffer(0);
		html.append(LABEL_HEADER_STYLES);
		html.append(messageResources.getMessage(locale, "label.mail.purchase.order.body.table.header"));
		detailTemplate = messageResources.getMessage(locale, "label.mail.purchase.order.body.table.detail");
		int index = 1;
		String classStyle = null;
		Iterator iteratorProduct = null;
		String products = null;
		ProductView productView = null;
		
		for (Iterator iter = instructionPurchaseFormDetails.iterator(); iter.hasNext();) {
			InstructionPurchaseDetailView element = (InstructionPurchaseDetailView) iter.next();
			if(index%2==0){
				classStyle = "columnadatoPar";
			}else{
				classStyle = "columnadatoNon";
			}
			iteratorProduct = element.getProductList().iterator();
			products = "";
			while(iteratorProduct.hasNext()){
				productView = (ProductView)iteratorProduct.next();
				products += productView.getProductId() + " - " + productView.getDescription() + "<br/>";
			}
			Object[] detailParams = {
					classStyle,
					StringUtils.leftPad(String.valueOf(index) , 3,"0"), 
					element.getCustomerView().getCustomerId(), 
					element.getCustomerView().getDescription(), 
					products,
					element.getItemQuantity(),
					element.getCornQuantity(),
					String.valueOf(element.getFutures()),
					String.valueOf(element.getTons()),
					messageResources.getMessage(locale, "label.futuretype." + element.getFutureTypeId()),
					messageResources.getMessage(locale,"label.strategyid." + element.getInstructionStrategyId()),
					messageResources.getMessage(locale,"label.strategytypeid." + element.getInstructionTypeId()),
					messageResources.getMessage(locale,"label.purchaseinstructiondetail.status." + element.getStatus()),
					};
					
			detail = MessageFormat.format(detailTemplate, detailParams);
			html.append(detail);
			index++;			
		}
		html.append(messageResources.getMessage(locale, "label.mail.purchase.order.body.table.footer"));
		return html.toString();
		
	}



	public Email buildMailForAddOrUpdateAction(int purchaseInstructionId, MessageResources messageResources, Locale locale, boolean addAction) {
		String purchaserMail = SystemParameterCollection.getInstance().getSystemParameterBean(CIMAPLANNING_PURCHASER_MAIL).getValue();
		String ccMail = SystemParameterCollection.getInstance().getSystemParameterBean(CIMMAPLANNINGMAIL_CC).getValue();
		String cimmaPlanningMail = SystemParameterCollection.getInstance().getSystemParameterBean(CIMAPLANNINGMAIL).getValue();
		String purchaserMails[];
		String ccMails[];
		InstructionPurchaseDetailService instructionPurchaseDetailService = null;		
		
		String subjectTemplate  = null;		
		String subject = null;
		String bodyTemplate = null;
		StringBuffer body = null;
		Email email = null;
		List instructionPurchaseFormDetails = null;
		subjectTemplate = messageResources.getMessage(locale, LABEL_SUBJECT_TEMPLATE);
		bodyTemplate = messageResources.getMessage(locale, LABEL_BODY_TEMPLATE);
		
		instructionPurchaseDetailService = new InstructionPurchaseDetailService();
		try {
			instructionPurchaseFormDetails = instructionPurchaseDetailService.list(purchaseInstructionId);			
		} catch (InstructionPurchaseDetailException e) {			
			e.printStackTrace();
		}
		
		if(addAction){
			Object[] paramsSubject = { messageResources.getMessage(locale, SUBJECT_ACTION_ADD),  StringUtils.leftPad(String.valueOf(purchaseInstructionId),3,"0")};
			Object[] paramsBody = { messageResources.getMessage(locale, BODY_ACTION_ADD)};
			subject = MessageFormat.format(subjectTemplate, paramsSubject);
			body = new StringBuffer(MessageFormat.format(bodyTemplate, paramsBody));			
		}else{
			Object[] paramsSubject = { messageResources.getMessage(locale, SUBJECT_ACTION_UPDATE), StringUtils.leftPad(String.valueOf(purchaseInstructionId),3,"0")};
			Object[] paramsBody = { messageResources.getMessage(locale,BODY_ACTION_UPDATE)};
			subject = MessageFormat.format(subjectTemplate, paramsSubject);
			body = new StringBuffer(MessageFormat.format(bodyTemplate, paramsBody));			
		}
		if(instructionPurchaseFormDetails!=null){
			body.append(purchaseOrderHTMLSimplified(instructionPurchaseFormDetails,messageResources,locale));
			
		}
		email = new Email();
		email.setFrom(cimmaPlanningMail);
		
		purchaserMails = purchaserMail.split(",");
		for (int index = 0; index < purchaserMails.length; index++) {
			email.addToRecipient(purchaserMails[index]);
		}

		ccMails = ccMail.split(",");
		for (int index = 0; index < ccMails.length; index++) {
			email.addCcRecipient(ccMails[index]);
		}
		
		email.setSubject(subject);
		email.setBody(body.toString());
		return email;
	}
}
